package com.riguz.forks.framework.mvc;

import javax.servlet.http.HttpServletRequest;

import com.riguz.forks.framework.mvc.view.ErrorResult;
import com.riguz.gags.base.Beans;
import com.riguz.gags.base.Strings;

public abstract class Controller {
    public Result error(int code, String message) {
        return new ErrorResult(code, message);
    }

    public String getParameter(String name) {
        HttpServletRequest request = RequestContext.getRequest();
        return request.getParameter(name);
    }

    public String[] getParameterValues(String name) {
        HttpServletRequest request = RequestContext.getRequest();
        return request.getParameterValues(name);
    }

    public String getParameter(String name, String defaultValue) {
        HttpServletRequest request = RequestContext.getRequest();
        String v = request.getParameter(name);
        if (Strings.isNullOrEmpty(v)) return defaultValue;
        return v;
    }

    public <T> T getParameterToBean(Class<T> beanClass, String prefix, String[] fields) {
        HttpServletRequest request = RequestContext.getRequest();
        try {
            return Beans.bind(beanClass, prefix, request.getParameterMap(), fields, false, true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
